package vg.services.graph_view_manager.realization.graph_view.smart_graph_view.realization.actions;

import vg.services.graph_view_manager.interfaces.graph_view.IGraphAction;
import vg.services.graph_view_manager.interfaces.graph_view.IGraphRenderer;
import vg.services.main_manager.MainManager;
import vg.services.progress_manager.interfaces.IProgressTask;
import vg.services.progress_manager.realization.DefaultProgressTask;

import javax.swing.*;

/**
 * It's default action for writing other actions.
 *
 * @author Timur Zolotuhin (e-mail: tzolotuhin@gmail.com)
 */
public abstract class DefaultAction implements IGraphAction {
	protected final DefaultProgressTask progress;	
	protected Object result = null;
	
	/**
	 * Constructor.
	 */
	public DefaultAction(String actionName) {
		progress = new DefaultProgressTask(actionName);
	}
		
	public Object getResult() {
		return result;
	}
	
	@Override
	public IProgressTask getProgressTask() {
		return progress;
	}

    @Override
    public void apply(final IGraphRenderer graphRenderer) {
        // execute no EDT action
        try {
            noEDTAction(graphRenderer);
        } catch (Throwable ex) {
            MainManager.logger.printException(ex);
        }

        // execute EDT action
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    try {
                        action(graphRenderer);
                    } catch (Throwable ex) {
                        MainManager.logger.printException(ex);
                    }
                }
            });
        } catch (Throwable ex) {
            MainManager.logger.printException(ex);
        }

        // finish action
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    try {
                        finishAction(graphRenderer);
                    } catch (Throwable ex) {
                        MainManager.logger.printException(ex);
                    }
                }
            });
        } catch (Throwable ex) {
            MainManager.logger.printException(ex);
        }
    }

    /**
     * Action, which will not called from EDT.
     */
    public abstract void noEDTAction(IGraphRenderer graphRenderer);

    /**
     * Action, which will called from EDT.
     */
    public abstract void action(IGraphRenderer graphRenderer);

    /**
     * Will called from EDT after process is finished.
     */
    public abstract void finishAction(IGraphRenderer graphRenderer);
}
